//
//  ByShapeBaseView.m
//  laserdevice_ios
//
//  Created by pro on 16/11/26.
//  Copyright © 2016年 com.itboye. All rights reserved.
//

#import "ByShapeBaseView.h"

// handle
#import "UIImage+ClipperExtends.h"  

// view
#import "ByUISceneAttributeMakeView.h"
#import "ByShapeBgView.h"       // 背景

@interface ByShapeBaseView ()

// 渲染视图（截屏展示用）
@property (nonatomic, strong) UIImageView *renderView;
@property (nonatomic, strong) UIImageView *renderContentView;
// 截屏视图（跟随手势移动）
@property (nonatomic, strong) UIImageView *clipperView;
// 原图内容展示视图（展示从相机或相册获取的图片）
@property (nonatomic, strong) UIImageView *baseImgView;
@property (nonatomic, strong) ByShapeLayerView *emptyView;

@property (nonatomic, strong) ByUISceneAttributeMakeView *attributeView;


@property (nonatomic, strong) UIImageView *testView;

@end

@implementation ByShapeBaseView
{
    
    NSTimer          *_timer;                           // 计时器
    __block CGFloat  _touchTime;                        // 点击时间（）
    BOOL             _allowEdit;                        // 是否允许编辑属性

//    NSMutableArray   *_models;                          // 模型数组
    NSMutableArray   *_revokeArray;                     // 撤销数组，最多存储10次
    NSMutableArray   *_resetArray;                      // 重做数组，最多存储10次

    ByShapeModel     *_selectedModel;                   // 模型数组

    BOOL             _allowModify;                      // 是否允许改变视图
    BOOL             _allowMove;                        // 是否允许拖曳整个视图

    NSInteger        _indexOfSelectedPoint;             // 记录当前选中点的索引
    
    CGVector         _touchOffsetForSelectedPoint;      // 选中的位移矢量
    
    CGPoint          _pointOfMoveFirst;                 // 记录上次移动的点
}
- (UIImageView *)renderView {
    
    if (!_renderView) {
        _renderView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
        _renderView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_renderView];
        _renderView.layer.borderColor = [UIColor orangeColor].CGColor;
        _renderView.layer.borderWidth = 2;
        
    }
    return _renderView;
}
- (UIImageView *)renderContentView {
    
    if (!_renderContentView) {
        _renderContentView = [[UIImageView alloc] initWithFrame:self.renderView.bounds];
        _renderContentView.contentMode = UIViewContentModeScaleAspectFit;
        [self.renderView addSubview:_renderContentView];
    }
    return _renderContentView;
}

- (ByUISceneAttributeMakeView *)attributeView {
    
    if (!_attributeView) {
        _attributeView = [[ByUISceneAttributeMakeView alloc] init];
        
    }
    return _attributeView;
}

- (ByShapeLayerView *)emptyView {
    
    if (!_emptyView) {
        CGFloat width = self.width;
        CGFloat height = self.height;
        
        UIBezierPath *path = [UIBezierPath bezierPath];
        for (int i = 0; i <= width; i += 8) {
            [path moveToPoint:CGPointMake(i, 0)];
            [path addLineToPoint:CGPointMake(i, height)];
        }
        for (int j = 0; j <= height; j += 8) {
            [path moveToPoint:CGPointMake(0, j)];
            [path addLineToPoint:CGPointMake(width, j)];
        }
        
        _emptyView = [[ByShapeLayerView alloc] init];
        _emptyView.shapeLayer.lineWidth = 0.5;
        _emptyView.shapeLayer.lineCap = kCALineCapRound;
        _emptyView.shapeLayer.lineJoin = kCALineJoinRound;
        _emptyView.shapeLayer.fillColor = [UIColor clearColor].CGColor;
        _emptyView.shapeLayer.strokeColor = [UIColor colorWithWhite:0.7 alpha:1].CGColor;
        _emptyView.opaque = NO;
        _emptyView.translatesAutoresizingMaskIntoConstraints = NO;
        
        _emptyView.shapeLayer.path = path.CGPath;

    }
    return _emptyView;
}



#pragma mark - 保存字典
- (NSMutableDictionary *)saveDictionary {
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:@"场景名称" forKey:@"name"];
    [dic setObject:[NSDate getCurrentDateForStringFormatWithFormatter:nil] forKey:@"create_time"];
    if (self.baseImg) {
        [dic setObject:@"./images/bg.png" forKey:@"background_img"];
    } else {
        [dic setObject:@"" forKey:@"background_img"];
    }
    
    NSMutableArray *images = [[NSMutableArray alloc] init];
    NSMutableArray *models = [[NSMutableArray alloc] init];

    int index = 1;
    for (ByShapeModel *model in _models) {
        NSMutableDictionary *tempDic = model.saveDictionary;
        UIImage *image = model.picture;
        if (image) {
            NSDictionary *resourceDic = @{
                                          @"id" : [NSString stringWithFormat:@"%i", index],
                                          @"type" : @"image",
                                          @"path" : [NSString stringWithFormat:@"./images/image%i.png", index]
                                          };
            [images addObject:resourceDic];
            
            [tempDic setObject:[NSString stringWithFormat:@"%i", index] forKey:@"image_id"];
            [tempDic setObject:[NSString stringWithFormat:@"./images/image%i.png", index] forKey:@"path"];

            index ++;
        } else {
            
            [tempDic setObject:@"-1" forKey:@"image_id"];
            [tempDic setObject:@"" forKey:@"path"];
        }
        
        [models addObject:tempDic];

    }
    [dic setObject:images.copy forKey:@"resource_list"];
    [dic setObject:models.copy forKey:@"element_list"];
    
    return dic;
}

- (NSArray *)shapeImages {
    
    NSMutableArray *temp = [[NSMutableArray alloc] init];
    for (ByShapeModel *model in _models) {
        if (model.picture) {
            [temp addObject:model.picture];
        }
    }
    return temp.copy;
}

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame jsonDic:(NSDictionary *)dic {
    
    if (self = [super initWithFrame:frame]) {
        
        [self addSubview:self.emptyView];
        
        self.backgroundColor = [UIColor whiteColor];

        // 关闭多点触摸
        self.multipleTouchEnabled = NO;
        self.userInteractionEnabled = YES;
        self.layer.masksToBounds = YES;
        self.contentMode = UIViewContentModeScaleAspectFit;
        self.layer.contentsGravity = kCAGravityResizeAspect;
        
        
        _models = [[NSMutableArray alloc] init];        // 初始化模型数组
        _revokeArray = [[NSMutableArray alloc] init];   // 初始化撤销数组
        _resetArray  = [[NSMutableArray alloc] init];   // 初始化重做数组
        
        // 根据json字典补充数据
        NSString *sceneName = dic[@"name"];
        NSString *bgImage = dic[@"background_img"];
        if (bgImage.length != 0) {
            self.baseImg = [ByFileManager getImageAtScene:sceneName imagePath:bgImage];
        }
        
        NSArray *modelDics = dic[@"element_list"];
        for (NSDictionary *modelDic in modelDics) {
            ByShapeModel *model = [[ByShapeModel alloc] initWithJsonDic:modelDic sceneName:sceneName];
            [_models addObject:model];
            [self addSubview:model.lineView];
            [self addSubview:model.pointView];
            [self addSubview:model.highLightLineView];
            if (model.angleView) {
                [self addSubview:model.angleView];
            }
            for (ByShapeLayerView *label in model.labels) {
                [self addSubview:label];
            }
        }
        
        ByShapeModel *lastModel = [_models lastObject];
        lastModel.selected = YES;
        _selectedModel = lastModel;
        
        // 绘制
        [self updatePaths];
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        [self addSubview:self.emptyView];

        self.backgroundColor = [UIColor whiteColor];
        
        // 关闭多点触摸
        self.multipleTouchEnabled = NO;
        self.userInteractionEnabled = YES;
        self.layer.masksToBounds = YES;
        self.contentMode = UIViewContentModeScaleAspectFit;
        self.layer.contentsGravity = kCAGravityResizeAspect;


        _models = [[NSMutableArray alloc] init];        // 初始化模型数组
        _revokeArray = [[NSMutableArray alloc] init];   // 初始化撤销数组
        _resetArray  = [[NSMutableArray alloc] init];   // 初始化重做数组

    }
    return self;
}


#pragma mark - 外部调用方法
// 添加模型
- (void)addShapeWithMode:(ByShapeMode)mode {
    
    [self changeRevokeArray:_models];
    
    for (ByShapeModel *model in _models) {
        model.selected = NO;
    }
    
    ByShapeModel *model = [[ByShapeModel alloc] initWithMode:mode];
    model.selected = YES;
    [_models addObject:model];
    [self addSubview:model.lineView];
    [self addSubview:model.pointView];
    [self addSubview:model.highLightLineView];
    if (model.angleView) {
        [self addSubview:model.angleView];
    }
    for (ByShapeLayerView *label in model.labels) {
        [self addSubview:label];
    }
    
    // 将刚创建的图层，作为选中的图层
    _selectedModel = model;

    [self updatePaths];
}

// 删除模型
- (void)deleteShape {
    
    [self changeRevokeArray:_models];

    if (!_selectedModel) {

        [UIAlertView showWithTitle:STRING(@"shanchu") message:STRING(@"shanchusuoyou") cancelButtonTitle:STRING(@"quxiao") otherButtonTitles:@[STRING(@"queding")] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                // 删除选中模型
                [_models removeAllObjects];
                for (UIView *subview in self.subviews) {
                    if ([subview isKindOfClass:[ByShapeLayerView class]] && subview != self.emptyView) {
                        [subview removeFromSuperview];
                    }
                }
            } else {
                return;
            }
        }];
        
    } else {
    
        // 删除选中模型
        [_models removeObject:_selectedModel];
        
        _selectedModel = nil;
        
        for (UIView *subview in self.subviews) {
            if ([subview isKindOfClass:[ByShapeLayerView class]] && subview != self.emptyView) {
                [subview removeFromSuperview];
            }
        }
        for (ByShapeModel *model in _models) {
            [self addSubview:model.lineView];
            [self addSubview:model.pointView];
            [self addSubview:model.highLightLineView];
            if (model.angleView) {
                [self addSubview:model.angleView];
            }
            for (ByShapeLayerView *label in model.labels) {
                [self addSubview:label];
            }
        }
    }
    
    // 重绘
    [self updatePaths];
}



- (void)revoke {
    
    if (_revokeArray.count == 0) {
        return;
    }
    
    // 把当前的模型数组存入重做数组中，用以重做
    [_resetArray addObject:_models];
    
    // 把当前的模型数组变为撤销数组的最后一个
    _models = [NSMutableArray arrayWithArray:[_revokeArray lastObject]];

    // 移除最后一步操作
    [_revokeArray removeLastObject];
    
    for (UIView *subview in self.subviews) {
        if ([subview isKindOfClass:[ByShapeLayerView class]] && subview != self.emptyView) {
            [subview removeFromSuperview];
        }
    }
    
    for (ByShapeModel *model in _models) {
        [self addSubview:model.lineView];
        [self addSubview:model.pointView];
        [self addSubview:model.highLightLineView];
        if (model.angleView) {
            [self addSubview:model.angleView];
        }
        for (ByShapeLayerView *label in model.labels) {
            [self addSubview:label];
        }
    }
    
    // 重绘
    [self updatePaths];
}

- (void)reset {
    
    if (_resetArray.count == 0) {
        return;
    }
    
    // 把当前的模型数组存入撤销数组中，用以撤销
    [self changeRevokeArray:_models];
    
    // 把当前的模型数组变为撤销数组的最后一个
    _models = [NSMutableArray arrayWithArray:[_resetArray lastObject]];
    
    // 移除最后一步操作
    [_resetArray removeLastObject];

    for (UIView *subview in self.subviews) {
        if ([subview isKindOfClass:[ByShapeLayerView class]] && subview != self.emptyView) {
            [subview removeFromSuperview];
        }
    }
    for (ByShapeModel *model in _models) {
        [self addSubview:model.pointView];
        [self addSubview:model.lineView];
        [self addSubview:model.highLightLineView];
        if (model.angleView) {
            [self addSubview:model.angleView];
        }
        for (ByShapeLayerView *label in model.labels) {
            [self addSubview:label];
        }
    }
    
    // 重绘
    [self updatePaths];
}

#pragma mark - 绘制
- (void)updatePaths {
    
    // 绘制图层
    [ByShapeDrawHandle drawShapeWithShapeModels:_models];
}

#pragma mark - 手势动作相关
// 开始点击
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    NSLog(@"begin");
    
    for (ByShapeModel *model in _models) {
        model.selected = NO;
    }
    _selectedModel = nil;
    
    _allowMove = NO;
    _allowEdit = NO;
    _allowModify = NO;

    // 当前点击点的位置
    NSValue *pointValue = [self pointValueWithTouches:touches];
    
    for (ByShapeModel *model in _models) {
        
        // 普通模型
        if (model.mode != ByShapeModeCuboids) {
            
            // 找到符合点击事件的点
            NSIndexSet *indexes = [model.points indexesOfObjectsPassingTest:^BOOL(NSValue *existingPointValue, NSUInteger idx, BOOL *stop) {
                CGPoint point = [pointValue CGPointValue];
                CGPoint existingPoint = [existingPointValue CGPointValue];
                CGFloat distance = ABS(point.x - existingPoint.x) + ABS(point.y - existingPoint.y);
                return distance < kDistanceThreshold;
            }];
            
            // 如果存在符合的点，则获得索引，和位移矢量，用于绘制
            if (indexes.count > 0) {
                _indexOfSelectedPoint = [indexes lastIndex];
                NSValue *existingPointValue = [model.points objectAtIndex:_indexOfSelectedPoint];
                CGPoint point = [pointValue CGPointValue];
                CGPoint existingPoint = [existingPointValue CGPointValue];
                _touchOffsetForSelectedPoint = CGVectorMake(point.x - existingPoint.x, point.y - existingPoint.y);
                
                // 设置操作属性
                _allowModify = YES;
                _allowMove = NO;
                _allowEdit = YES;
                
                // 改变当前选中视图
                _selectedModel = model;
                for (ByShapeModel *model in _models) {
                    model.selected = NO;
                }
                _selectedModel.selected = YES;
                
                // 记录该操作前的模型数组，用于撤销
                [self changeRevokeArray:_models];
                
                if (SYSTEM_VERSION_GREATER_THAN(@"10.0")) {
                    _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 repeats:YES block:^(NSTimer * _Nonnull timer) {
                        _touchTime += 0.01;
                    }];
                } else {
                    _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
                }
                [_timer fire];
                
                break;      // 跳出循环，因为已经找到了适合的点
            } else {
                _allowModify = NO;
                _allowMove = NO;
                _allowEdit = NO;
            }
            
            
        }
        
        // 立方体
        else {
         
            // 找到符合点击事件的点
            NSIndexSet *indexes = [model.cuboidsControllPoints indexesOfObjectsPassingTest:^BOOL(NSValue *existingPointValue, NSUInteger idx, BOOL *stop) {
                CGPoint point = [pointValue CGPointValue];
                CGPoint existingPoint = [existingPointValue CGPointValue];
                CGFloat distance = ABS(point.x - existingPoint.x) + ABS(point.y - existingPoint.y);
                return distance < kDistanceThreshold;
            }];
            
            // 如果存在符合的点，则获得索引，和位移矢量，用于绘制
            if (indexes.count > 0) {
                _indexOfSelectedPoint = [indexes lastIndex];
                NSValue *existingPointValue = [model.cuboidsControllPoints objectAtIndex:_indexOfSelectedPoint];
                CGPoint point = [pointValue CGPointValue];
                CGPoint existingPoint = [existingPointValue CGPointValue];
                _touchOffsetForSelectedPoint = CGVectorMake(point.x - existingPoint.x, point.y - existingPoint.y);
                
                // 设置操作属性
                _allowModify = YES;
                _allowMove = NO;
                _allowEdit = YES;

                // 改变当前选中视图
                _selectedModel = model;
                for (ByShapeModel *model in _models) {
                    model.selected = NO;
                }
                _selectedModel.selected = YES;
                
                // 记录该操作前的模型数组，用于撤销
                [self changeRevokeArray:_models];
                
                if (SYSTEM_VERSION_GREATER_THAN(@"10.0")) {
                    _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 repeats:YES block:^(NSTimer * _Nonnull timer) {
                        _touchTime += 0.01;
                    }];
                } else {
                    _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
                }
                [_timer fire];
                
                break;      // 跳出循环，因为已经找到了适合的点
            } else {
                _allowModify = NO;
                _allowMove = NO;
                _allowEdit = NO;
            }

        }
       
    }
    
    
    for (ByShapeModel *model in _models) {
        
        
        // 如果不能修改编辑，则查看是不是能移动
        if (!_allowModify) {
            CGPoint point = [pointValue CGPointValue];
            bool isContain = NO;
            
            if (model.mode == ByShapeModeCuboids) {
                for (UIBezierPath *path in model.movePaths) {
                    if ([path containsPoint:point]) {
                        NSLog(@"####");
                        isContain = YES;
                        break;
                    }
                }
            } else {
                if ([model.movePath containsPoint:point]) {
                    NSLog(@"####");
                    isContain = YES;
                }
            }
            

            // 如果存在符合的点，则获得索引，和位移矢量，用于绘制
            if (isContain == YES) {
                
                _pointOfMoveFirst = point;
                
                // 设置操作属性
                _allowMove = YES;
                _allowEdit = YES;
                
                // 改变当前选中视图
                _selectedModel = model;
                for (ByShapeModel *model in _models) {
                    model.selected = NO;
                }
                _selectedModel.selected = YES;
                
                // 记录该操作前的模型数组，用于撤销
                [self changeRevokeArray:_models];
                
                if (SYSTEM_VERSION_GREATER_THAN(@"10.0")) {
                    _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 repeats:YES block:^(NSTimer * _Nonnull timer) {
                        _touchTime += 0.01;
                    }];
                } else {
                    _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
                }
                [_timer fire];
                
                break;
            } else {
                _allowMove = NO;
                _allowEdit = NO;
            }
        }
       
        
    }
    
    // 绘制
    [self updatePaths];
    
}
- (void)timerAction {
    _touchTime += 0.01;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    // 编辑
    if (_allowModify) {
        
        // 只有在编辑的时候才会显示，大图
        self.renderView.hidden = NO;
        [self bringSubviewToFront:self.renderView];
        [self showClipImageView:touches];

        // 普通模型编辑
        if (_selectedModel.mode != ByShapeModeCuboids) {
            NSValue *pointValue = [self pointValueWithTouches:touches];
            
            // 校正偏移量
            NSValue *offsetPointValue = [self pointValueByRemovingOffset:_touchOffsetForSelectedPoint fromPointValue:pointValue];
            [_selectedModel.points replaceObjectAtIndex:_indexOfSelectedPoint withObject:offsetPointValue];
            
            _selectedModel.movePath = [_selectedModel movePathForNormal];
            
            [self updatePaths];
        }
    
        // 立方体编辑（需要判断编辑点，知道是控制长，宽，高，整体）
        // 长：左侧四个点拥有一样的偏移（up：0，1  down：0，1）
        // 宽：后侧四个点拥有一样的偏移（up：3，0  down：3，0）
        // 高：上侧四个点拥有一样的偏移（up：全部  down：无）
        // 整体：四个对角点拥有相反的偏移（up：0，1，3  down：0）
        else {
            NSValue *pointValue = [self pointValueWithTouches:touches];
            // 校正偏移量
            NSValue *offsetPointValue = [self pointValueByRemovingOffset:_touchOffsetForSelectedPoint fromPointValue:pointValue];
            
            if (_indexOfSelectedPoint == 0) {   // 长
                NSValue *usePointValue1 = [self pointValueByAdjustForCuboidsWithPoint:_selectedModel.cuboidsDrawUpPoints[0] point2:_selectedModel.cuboidsControllPoints[0] basePointValue:offsetPointValue];
                [_selectedModel.cuboidsDrawUpPoints replaceObjectAtIndex:0 withObject:usePointValue1];
                
                NSValue *usePointValue2 = [self pointValueByAdjustForCuboidsWithPoint:_selectedModel.cuboidsDrawUpPoints[1] point2:_selectedModel.cuboidsControllPoints[0] basePointValue:offsetPointValue];
                [_selectedModel.cuboidsDrawUpPoints replaceObjectAtIndex:1 withObject:usePointValue2];
                
                NSValue *usePointValue3 = [self pointValueByAdjustForCuboidsWithPoint:_selectedModel.cuboidsDrawDownPoints[0] point2:_selectedModel.cuboidsControllPoints[0] basePointValue:offsetPointValue];
                [_selectedModel.cuboidsDrawDownPoints replaceObjectAtIndex:0 withObject:usePointValue3];
                
                NSValue *usePointValue4 = [self pointValueByAdjustForCuboidsWithPoint:_selectedModel.cuboidsDrawDownPoints[1] point2:_selectedModel.cuboidsControllPoints[0] basePointValue:offsetPointValue];
                [_selectedModel.cuboidsDrawDownPoints replaceObjectAtIndex:1 withObject:usePointValue4];
            }
            if (_indexOfSelectedPoint == 1) {   // 宽
                
                NSValue *usePointValue1 = [self pointValueByAdjustForCuboidsWithPoint:_selectedModel.cuboidsDrawUpPoints[0] point2:_selectedModel.cuboidsControllPoints[1] basePointValue:offsetPointValue];
                [_selectedModel.cuboidsDrawUpPoints replaceObjectAtIndex:0 withObject:usePointValue1];
                
                NSValue *usePointValue2 = [self pointValueByAdjustForCuboidsWithPoint:_selectedModel.cuboidsDrawUpPoints[3] point2:_selectedModel.cuboidsControllPoints[1] basePointValue:offsetPointValue];
                [_selectedModel.cuboidsDrawUpPoints replaceObjectAtIndex:3 withObject:usePointValue2];
                
                NSValue *usePointValue3 = [self pointValueByAdjustForCuboidsWithPoint:_selectedModel.cuboidsDrawDownPoints[0] point2:_selectedModel.cuboidsControllPoints[1] basePointValue:offsetPointValue];
                [_selectedModel.cuboidsDrawDownPoints replaceObjectAtIndex:0 withObject:usePointValue3];
                
                NSValue *usePointValue4 = [self pointValueByAdjustForCuboidsWithPoint:_selectedModel.cuboidsDrawDownPoints[3] point2:_selectedModel.cuboidsControllPoints[1] basePointValue:offsetPointValue];
                [_selectedModel.cuboidsDrawDownPoints replaceObjectAtIndex:3 withObject:usePointValue4];
            }
            if (_indexOfSelectedPoint == 2) {   // 高
                
                NSValue *usePointValue1 = [self pointValueByAdjustForCuboidsWithPoint:_selectedModel.cuboidsDrawUpPoints[0] point2:_selectedModel.cuboidsControllPoints[2] basePointValue:offsetPointValue];
                [_selectedModel.cuboidsDrawUpPoints replaceObjectAtIndex:0 withObject:usePointValue1];
                
                NSValue *usePointValue2 = [self pointValueByAdjustForCuboidsWithPoint:_selectedModel.cuboidsDrawUpPoints[1] point2:_selectedModel.cuboidsControllPoints[2] basePointValue:offsetPointValue];
                [_selectedModel.cuboidsDrawUpPoints replaceObjectAtIndex:1 withObject:usePointValue2];
                
                NSValue *usePointValue3 = [self pointValueByAdjustForCuboidsWithPoint:_selectedModel.cuboidsDrawUpPoints[2] point2:_selectedModel.cuboidsControllPoints[2] basePointValue:offsetPointValue];
                [_selectedModel.cuboidsDrawUpPoints replaceObjectAtIndex:2 withObject:usePointValue3];
                
                NSValue *usePointValue4 = [self pointValueByAdjustForCuboidsWithPoint:_selectedModel.cuboidsDrawUpPoints[3] point2:_selectedModel.cuboidsControllPoints[2] basePointValue:offsetPointValue];
                [_selectedModel.cuboidsDrawUpPoints replaceObjectAtIndex:3 withObject:usePointValue4];
            }
            if (_indexOfSelectedPoint == 3) {   // 整体
                
                NSValue *usePointValue0 = [self pointValueByAdjustForCuboidsWithPoint:_selectedModel.cuboidsDrawDownPoints[2] point2:_selectedModel.cuboidsControllPoints[3] basePointValue:offsetPointValue];
                [_selectedModel.cuboidsDrawDownPoints replaceObjectAtIndex:2 withObject:usePointValue0];
                
                // up：1
                NSValue *reverseOffsetPointValue = [self pointValueHuodeZhengtiDeSigedianDeFangfa:usePointValue0 value1:_selectedModel.cuboidsControllPoints[0] value2:_selectedModel.cuboidsControllPoints[2]];
                [_selectedModel.cuboidsDrawUpPoints replaceObjectAtIndex:1 withObject:reverseOffsetPointValue];
                
                // up：3
                reverseOffsetPointValue = [self pointValueHuodeZhengtiDeSigedianDeFangfa:usePointValue0 value1:_selectedModel.cuboidsControllPoints[1] value2:_selectedModel.cuboidsControllPoints[2]];
                [_selectedModel.cuboidsDrawUpPoints replaceObjectAtIndex:3 withObject:reverseOffsetPointValue];
                
                // down：0
                reverseOffsetPointValue = [self pointValueHuodeZhengtiDeSigedianDeFangfa:usePointValue0 value1:_selectedModel.cuboidsControllPoints[0] value2:_selectedModel.cuboidsControllPoints[1]];
                [_selectedModel.cuboidsDrawDownPoints replaceObjectAtIndex:0 withObject:reverseOffsetPointValue];

                // up：0
                reverseOffsetPointValue = [self pointValueHuodeZhengtiDeSigedianDeFangfa:usePointValue0 value1:_selectedModel.cuboidsControllPoints[2] value2:reverseOffsetPointValue];
                [_selectedModel.cuboidsDrawUpPoints replaceObjectAtIndex:0 withObject:reverseOffsetPointValue];
                
                
            }
            
            [_selectedModel.cuboidsControllPoints replaceObjectAtIndex:_indexOfSelectedPoint withObject:offsetPointValue];

//            _selectedModel.movePath = [_selectedModel movePathForCuboids];
            _selectedModel.movePaths = [_selectedModel movePathsForCuboids];
            
            [self updatePaths];

        }
    }
    
    
    // 移动
    if (_allowMove) {
        
        self.renderView.hidden = YES;
        
        if (_selectedModel.mode != ByShapeModeCuboids) {
            for (int i = 0; i < _selectedModel.points.count; i ++) {
                NSValue *pointValue = [self pointValueWithTouches:touches];
                CGPoint point = pointValue.CGPointValue;

                CGPoint point2 = _pointOfMoveFirst;
                
                NSValue *pointValue3 = _selectedModel.points[i];
                CGPoint point3 = pointValue3.CGPointValue;
                point3.x += (point.x - point2.x);
                point3.y += (point.y - point2.y);
                pointValue3 = [NSValue valueWithCGPoint:point3];
                
                NSValue *offsetPointValue = [self pointValueByRemovingOffset:CGVectorMake(0, 0) fromPointValue:pointValue3];

                [_selectedModel.points replaceObjectAtIndex:i withObject:offsetPointValue];
            }
            NSValue *pointValue = [self pointValueWithTouches:touches];
            _pointOfMoveFirst = pointValue.CGPointValue;

            _selectedModel.movePath = [_selectedModel movePathForNormal];
            
            [self updatePaths];
        }
        
        else {
            
            for (int i = 0; i < _selectedModel.cuboidsDrawUpPoints.count; i ++) {
                NSValue *pointValue = [self pointValueWithTouches:touches];
                CGPoint point = pointValue.CGPointValue;

                CGPoint point2 = _pointOfMoveFirst;
                
                NSValue *pointValue3 = _selectedModel.cuboidsDrawUpPoints[i];
                CGPoint point3 = pointValue3.CGPointValue;
                point3.x += (point.x - point2.x);
                point3.y += (point.y - point2.y);
                pointValue3 = [NSValue valueWithCGPoint:point3];
                
                NSValue *offsetPointValue = [self pointValueByRemovingOffset:CGVectorMake(0, 0) fromPointValue:pointValue3];
                
                [_selectedModel.cuboidsDrawUpPoints replaceObjectAtIndex:i withObject:offsetPointValue];
            }
            
            for (int i = 0; i < _selectedModel.cuboidsDrawDownPoints.count; i ++) {
                NSValue *pointValue = [self pointValueWithTouches:touches];
                CGPoint point = pointValue.CGPointValue;

                CGPoint point2 = _pointOfMoveFirst;

                NSValue *pointValue3 = _selectedModel.cuboidsDrawDownPoints[i];
                CGPoint point3 = pointValue3.CGPointValue;
                point3.x += (point.x - point2.x);
                point3.y += (point.y - point2.y);
                pointValue3 = [NSValue valueWithCGPoint:point3];
                
                NSValue *offsetPointValue = [self pointValueByRemovingOffset:CGVectorMake(0, 0) fromPointValue:pointValue3];
                
                [_selectedModel.cuboidsDrawDownPoints replaceObjectAtIndex:i withObject:offsetPointValue];
            }
            
            for (int i = 0; i < _selectedModel.cuboidsControllPoints.count; i ++) {
                NSValue *pointValue = [self pointValueWithTouches:touches];
                CGPoint point = pointValue.CGPointValue;

                CGPoint point2 = _pointOfMoveFirst;

                NSValue *pointValue3 = _selectedModel.cuboidsControllPoints[i];
                CGPoint point3 = pointValue3.CGPointValue;
                point3.x += (point.x - point2.x);
                point3.y += (point.y - point2.y);
                pointValue3 = [NSValue valueWithCGPoint:point3];
                
                NSValue *offsetPointValue = [self pointValueByRemovingOffset:CGVectorMake(0, 0) fromPointValue:pointValue3];
                
                [_selectedModel.cuboidsControllPoints replaceObjectAtIndex:i withObject:offsetPointValue];
            }
            
            NSValue *pointValue = [self pointValueWithTouches:touches];
            _pointOfMoveFirst = pointValue.CGPointValue;

//            _selectedModel.movePath = [_selectedModel movePathForCuboids];
            _selectedModel.movePaths = [_selectedModel movePathsForCuboids];

            [self updatePaths];
        }
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
//    [self touchesMoved:touches withEvent:event];
    
    self.renderView.hidden = YES;
    
    // 只要有一次编辑或移动操作，则清空重做数组
    [_resetArray removeAllObjects];
    
    // 如果touchTime < 0.1秒，就承认是点击，并且点击不属于撤销行列
    if (_touchTime < 0.25 && _allowEdit) {
        
        // 点击不属于可撤销行列
        [_revokeArray removeLastObject];

        // 展示属性设置视图
        [self.attributeView showWithShapeModel:_selectedModel];
        __weak typeof(_selectedModel) weakModel = _selectedModel;
        __weak typeof(self) weakself = self;

        [self.attributeView setBackAction:^(NSString *name, NSArray *attributes, UIImage *picture) {
            weakModel.name = name;
            weakModel.attributes = [NSMutableArray arrayWithArray:attributes];
            if (picture) {
                weakModel.picture = picture;
            }
        }];
        [self.attributeView setSelectPictureBlock:^{
            if (weakself.selectPictureBlock) {
                weakself.selectPictureBlock();
            }
        }];
    }
    _touchTime = 0.00;
    [_timer invalidate];
    _timer = nil;
    
}




#pragma mark - 辅助
- (NSValue *)pointValueWithTouches:(NSSet *)touches {
    
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    
    CGPoint converPoint = [self convertPoint:point toView:self.baseImgView];
    if (![self.baseImgView pointInside:converPoint withEvent:nil]) {
        if (converPoint.y >= self.baseImgView.height) {
            point.y = self.baseImgView.bottom;
        } else {
            point.y = self.baseImgView.top;
        }
    }
    return [NSValue valueWithCGPoint:point];
}

- (NSValue *)pointValueByRemovingOffset:(CGVector)offset fromPointValue:(NSValue *)pointValue {
    
    CGPoint point = [pointValue CGPointValue];
    CGPoint offsetPoint = CGPointMake(point.x - offset.dx, point.y - offset.dy);
    return [NSValue valueWithCGPoint:offsetPoint];
}

- (NSValue *)pointValueByAdjustForCuboidsWithPoint:(NSValue *)pointValue1 point2:(NSValue *)pointValue2 basePointValue:(NSValue *)basePointValue  {
    
    
    CGPoint point1 = [pointValue1 CGPointValue];
    CGPoint point2 = [pointValue2 CGPointValue];
    CGPoint basePoint = [basePointValue CGPointValue];
    CGPoint retPoint = CGPointMake(point1.x - point2.x + basePoint.x, point1.y - point2.y + basePoint.y);
    return [NSValue valueWithCGPoint:retPoint];
}

- (NSValue *)pointValueHuodeZhengtiDeSigedianDeFangfa:(NSValue *)baseValue
                                               value1:(NSValue *)value1
                                               value2:(NSValue *)value2 {
    
    CGPoint basePoint = [baseValue CGPointValue];
    CGPoint point1 = [value1 CGPointValue];
    CGPoint point2 = [value2 CGPointValue];
    
    CGVector v1 = CGVectorMake(point1.x - basePoint.x, point1.y - basePoint.y);
    CGVector v2 = CGVectorMake(point2.x - basePoint.x, point2.y - basePoint.y);
    
    CGPoint retPoint = CGPointMake(basePoint.x + v1.dx + v2.dx, basePoint.y + v1.dy + v2.dy);
    
    return [NSValue valueWithCGPoint:retPoint];
}

- (void)changeRevokeArray:(NSMutableArray *)models {
    
    NSMutableArray *temp;
    temp = models.mutableCopy;
    
    if ([models containsObject:_selectedModel]) {
        NSInteger index = [models indexOfObject:_selectedModel];
        [temp replaceObjectAtIndex:index withObject:_selectedModel.copy];
        
    }
    
//    if (_revokeArray.count == 10) {
//        [_revokeArray removeObjectAtIndex:0];
//    }
    [_revokeArray addObject:temp];
}



#pragma mark - 截屏相关
- (void)showClipImageView:(NSSet *)touches {
    
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    // 使截屏范围仅在图片内容范围内，超出范围强行设置截屏范围
    CGPoint converPoint = [self convertPoint:point toView:self.baseImgView];
    if (![self.baseImgView pointInside:converPoint withEvent:nil]) {
        if (converPoint.y >= self.baseImgView.height) {
            point.y = self.baseImgView.bottom;
        } else {
            point.y = self.baseImgView.top;
        }
    }
    // 设置截屏视图的范围，用来截取对应区域的视图图片
    self.clipperView.origin = CGPointMake(point.x - self.clipperView.width / 2,
                                          point.y - self.clipperView.height / 2);
    // 获得截屏图片
    UIImage *image = [self clipImgForCopy];
    // 把渲染区域的内容视图用截屏图片赋值
    self.renderContentView.image = image;
    // 处理图片超出部分
    if (image.size.width > image.size.height) {
        if (point.y < self.height / 2) {
            self.renderContentView.frame = CGRectMake(0, 0, self.renderView.width, self.renderView.width * image.size.height / image.size.width);
            self.renderContentView.bottom = self.renderView.height;
        } else {
            self.renderContentView.frame = CGRectMake(0, 0, self.renderView.width, self.renderView.width * image.size.height / image.size.width);
        }
    } else {
        if (point.x < self.width / 2) {
            self.renderContentView.frame = CGRectMake(0, 0, self.renderView.height * image.size.width / image.size.height, self.renderView.height);
            self.renderContentView.right = self.renderView.width;
        } else {
            self.renderContentView.frame = CGRectMake(0, 0, self.renderView.height * image.size.width / image.size.height, self.renderView.height);
        }
    }
    
    // 处理为了不让渲染视图遮挡截屏视图，根据截屏视图的位置，调整渲染视图的位置
    CGPoint point1 = CGPointMake(point.x - self.clipperView.width / 2, point.y - self.clipperView.height / 2);
    CGPoint point2 = CGPointMake(point.x + self.clipperView.width / 2, point.y - self.clipperView.height / 2);
    CGPoint point3 = CGPointMake(point.x - self.clipperView.width / 2, point.y + self.clipperView.height / 2);
    CGPoint point4 = CGPointMake(point.x + self.clipperView.width / 2, point.y + self.clipperView.height / 2);

    if (![self.renderView pointInside:point1 withEvent:nil] &&
        ![self.renderView pointInside:point2 withEvent:nil] &&
        ![self.renderView pointInside:point3 withEvent:nil] &&
        ![self.renderView pointInside:point4 withEvent:nil] ) {
        self.renderView.left = 10;
    } else {
        self.renderView.right = self.width - 10;
    }
}
- (UIImageView *)clipperView {
    if (!_clipperView) {
        
        _clipperView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];

        [self addSubview:_clipperView];
    }
    return _clipperView;
}
- (UIImageView *)baseImgView {
    if (!_baseImgView) {
        _baseImgView = [[UIImageView alloc] initWithFrame:self.bounds];
        _baseImgView.tag = 111;
        [self addSubview:_baseImgView];
        [self sendSubviewToBack:_baseImgView];
    }
    return _baseImgView;
}

- (void)setBaseImg:(UIImage *)baseImg {
    
    _baseImg = baseImg;
    
    [self.emptyView removeFromSuperview];
//    [self bringSubviewToFront:self.emptyView];
    
    // 调整背景图片大小
    CGFloat width = _baseImg.size.width;
    CGFloat height = _baseImg.size.height;
    if (width != self.frame.size.width) {
        width = self.frame.size.width;
    }
    height = _baseImg.size.height / _baseImg.size.width * width;
    
    if (height < self.clipperView.frame.size.height) {
        height = self.clipperView.frame.size.height;
    }
    
    width = _baseImg.size.width / _baseImg.size.height * height;
    UIImage *img = [_baseImg scaledToSize:CGSizeMake(width, height) withScale:NO];
    
    self.baseImgView.image = img;
    self.baseImgView.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    self.baseImgView.y     = self.height / 2;
    

  
}

// 拷贝本view的layer上渲染的视图
- (UIImage *)copyImg {
    
    UIGraphicsBeginImageContext(self.bounds.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CGFloat scale = [UIScreen mainScreen].scale * img.size.width/self.frame.size.width;
    
    CGRect rect = self.bounds;
    CGRect rect2 = CGRectMake(rect.origin.x * scale, rect.origin.y * scale, scale *rect.size.width, scale * rect.size.height);
    CGImageRef cgImg = CGImageCreateWithImageInRect(img.CGImage, rect2);
    
    UIImage *copyImg = [UIImage imageWithCGImage:cgImg];
    
    CGImageRelease(cgImg);
    
    return copyImg;
}
// 根据拷贝的本视图图片和截屏视图的位置，来获取截屏图片
- (UIImage *)clipImgForCopy {
    
    UIImage *copyImg = [self copyImg];
    
    CGRect rect = [self convertRect:self.clipperView.frame toView:self];
    CGRect rect2 = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);

    CGImageRef cgImg = CGImageCreateWithImageInRect(copyImg.CGImage, rect2);
    UIImage *clippedImg = [UIImage imageWithCGImage:cgImg];
    
    CGImageRelease(cgImg);
    return clippedImg;
}
@end
